<?php
/**
 * Created by PhpStorm
 * User: hean
 * Date: 2017/11/7
 * Time: 15:31
 */

namespace app\index\controller;

use app\index\model\Goods;
use think\Controller;
use think\Cookie;
use think\Request;

use app\index\model\Users as UserModel;
use app\index\model\Shoper as ShoperModel;
use app\index\model\Admin as AdminModel;
use app\index\model\Area as AreaModel;
use app\index\model\Receive as ReceiveModel;
use app\index\model\Cart as CartModel;
use app\index\model\Attr as AttrModel;
use app\index\model\Goods as GoodsModel;
use app\index\model\Transfer as TransferModel;
use app\index\model\Pay as PayModel;
use app\index\model\Order as OrderModel;
use app\index\model\OrderDetail as OrderDetailModel;

class Person extends Controller
{

	//首页---------------------------------------------------------------------------------
	public function index()
	{
		return $this->fetch();
	}


	//个人信息页----------------------------------------------------------------------------
	public function information()
	{
		$loginType = Cookie::get('loginType');    //区别哪张表
		$loginBy = Cookie::get('loginBy');    //区别哪种方式登录
		if ($loginType == 0) {    //用户表
			if ($loginBy == 'tel') {    //电话号登录
				$tel = Cookie::get('tel');
				$userData = UserModel::get(['phone' => $tel]);
			}
			if ($loginBy == 'email') {    //邮箱登录
				$email = Cookie::get('email');
				$userData = UserModel::get(['email' => $email]);
			}
			if ($loginBy == 'username') {    //用户名登录
				$username = Cookie::get('username');
				$userData = UserModel::get(['username' => $username]);
			}

			$infoData['username'] = $userData->username;
			$infoData['realname'] = $userData->real_name;
			$infoData['sex'] = $userData->sex;
			$infoData['year'] = date('Y', strtotime($userData->birthday));
			$infoData['month'] = date('m', strtotime($userData->birthday));
			$infoData['day'] = date('d', strtotime($userData->birthday));
			$infoData['tel'] = $userData->phone;
			$infoData['email'] = $userData->email;
		} else if ($loginType == 1) {    //商家表
			if ($loginBy == 'tel') {    //电话号登录
				$tel = Cookie::get('tel');
				$userData = ShoperModel::get(['shop_phone' => $tel]);
			}
			if ($loginBy == 'email') {    //邮箱登录
				$email = Cookie::get('email');
				$userData = ShoperModel::get(['shop_email' => $email]);
			}
			if ($loginBy == 'username') {    //用户名登录
				$username = Cookie::get('username');
				$userData = ShoperModel::get(['shop_name' => $username]);
			}

			$infoData['username'] = $userData->shop_name;
			$infoData['realname'] = $userData->shoper_name;
			$infoData['sex'] = $userData->sex;
			$infoData['year'] = date('Y', strtotime($userData->birthday));
			$infoData['month'] = date('m', strtotime($userData->birthday));
			$infoData['day'] = date('d', strtotime($userData->birthday));
			$infoData['tel'] = $userData->shop_phone;
			$infoData['email'] = $userData->shop_email;
		}


		$this->assign('infoData', $infoData);

		return $this->fetch();
	}

	//检查修改后的用户名是否可用
	public function nameCheck(Request $request)
	{
		$name = $request->post('name');
		$loginType = Cookie::get('loginType');
		$userResult = UserModel::where(['username' => $name])->select();
		$shopResult = ShoperModel::where(['shop_name' => $name])->select();
		$adminResult = AdminModel::where(['admin_name' => $name])->select();
		$cookieid = Cookie::get('uid');
		if ($loginType == 0) {
			$uid = null;
			if ($userResult) {
				foreach ($userResult as $val) {
					$uid = $val->uid;
				}
			}
			if ($uid == $cookieid) {
				$userResult = false;
			}
		} else if ($loginType == 1) {
			$shopid = null;
			if ($shopResult) {
				foreach ($shopResult as $val) {
					$shopid = $val->shop_id;
				}
			}
			if ($shopid == $cookieid) {
				$shopResult = false;
			}
		} else if ($loginType == 2) {
			$adminid = null;
			if ($adminResult) {
				foreach ($adminResult as $val) {
					$adminid = $val->admin_id;
				}
			}
			if ($adminid == $cookieid) {
				$adminResult = false;
			}
		}
		if ($userResult || $shopResult || $adminResult) {
			echo json_encode(['value' => 1]);
		} else {
			echo json_encode(['value' => 2]);
		}
	}


	//检查修改后的电话是否可用
	public function telCheck(Request $request)
	{
		$tel = $request->post('phone');
		$userResult = UserModel::get(['phone' => $tel]);
		$shopResult = ShoperModel::get(['shop_phone' => $tel]);
		$adminResult = AdminModel::get(['admin_phone' => $tel]);
		$loginType = Cookie::get('loginType');
		$cookid = Cookie::get('uid');
		if ($loginType == 0) {
			if ($userResult) {
				$phone = $userResult->uid;
				if ($phone == $cookid) {
					$userResult = false;
				}
			}
		} else if ($loginType == 1) {
			if ($shopResult) {
				$shopid = $shopResult->shop_id;
				if ($shopid == $cookid) {
					$shopResult = false;
				}
			}
		} else if ($loginType == 2) {
			if ($adminResult) {
				$adminid = $adminResult->admin_id;
				if ($adminid == $cookid) {
					$adminResult = false;
				}
			}
		}
		if ($userResult || $shopResult || $adminResult) {
			echo json_encode(['value' => 3]);
		} else {
			echo json_encode(['value' => 4]);
		}
	}

	//检查邮箱是否可用
	public function emailCheck(Request $request)
	{
		$email = $request->post('email');
		$userResult = UserModel::get(['email' => $email]);
		$shopResult = ShoperModel::get(['shop_email' => $email]);
		$adminResult = AdminModel::get(['admin_email' => $email]);

		$loginType = Cookie::get('loginType');
		$cookid = Cookie::get('uid');
		if ($loginType == 0) {
			if ($userResult) {
				$uid = $userResult->uid;
				if ($uid == $cookid) {
					$userResult = false;
				}
			}
		} else if ($loginType == 1) {
			if ($shopResult) {
				$shopid = $shopResult->shop_id;
				if ($shopid == $cookid) {
					$shopResult = false;
				}
			}
		} else if ($loginType == 2) {
			if ($adminResult) {
				$adminid = $adminResult->admin_id;
				if ($adminid == $cookid) {
					$adminResult = false;
				}
			}
		}
		if ($userResult || $shopResult || $adminResult) {
			echo json_encode(['value' => 5]);
		} else {
			echo json_encode(['value' => 6]);
		}
	}

	//修改信息更新数据库
	public function upInfo(Request $request)
	{
		$nick = $request->post('nick');
		$name = $request->post('name');
		$sex = $request->post('sex');
		$birthday = $request->post('birthday');
		$tel = $request->post('tel');
		$email = $request->post('email');

		$loginType = Cookie::get('loginType');
		$uid = Cookie::get('uid');
		if ($loginType == 0) {
			$data['username'] = $nick;
			$data['real_name'] = $name;
			$data['sex'] = $sex;
			$data['phone'] = $tel;
			$data['birthday'] = $birthday;
			$data['email'] = $email;
			$userResult = UserModel::get(['uid' => $uid]);
			$oldEmail = $userResult->email;
			if ($oldEmail != $email) {
				$data['id_active'] = 0;
			}
			$result = UserModel::where('uid', $uid)->update($data);
			if ($result) {
				Cookie::set('username', $nick);
				echo json_encode(['value' => 7]);
			} else {
				echo json_encode(['value' => 8]);
			}

		}
		if ($loginType == 1) {
			$data['shop_name'] = $nick;
			$data['shoper_name'] = $name;
			$data['sex'] = $sex;
			$data['birthday'] = $birthday;
			$data['shop_phone'] = $tel;
			$data['shop_email'] = $email;

			$shopResult = ShoperModel::get(['shop_id' => $uid]);
			$oldEmail = $shopResult->shop_email;
			if ($oldEmail != $email) {
				$data['is_active'] = 0;
			}

			$result = ShoperModel::where('shop_id', $uid)->update($data);
			if ($result) {
				Cookie::set('username', $nick);
				echo json_encode(['value' => 7]);
			} else {
				echo json_encode(['value' => 8]);
			}
		}
	}


	//地址管理---------------------------------------------------------------------------
	public function address()
	{
		$area0 = AreaModel::where(['area_deepth' => 0])->field('area_id, pid, area_name')->select();
		$this->assign('area0', $area0);

		//查询收件人地址
		$uid = Cookie::get('uid');
		$result = ReceiveModel::where(['uid' => $uid, 'receive_del' => 0])->select();
		if ($result) {
			foreach ($result as $val) {
				if ($val->is_default == 1) {
					$datano['receive_id'] = $val->receive_id;
					$datano['receive_name'] = $val->receive_name;
					$datapre1 = explode('_', $val->receive_address)[1];
					$datapre2 = explode('_', $val->receive_address)[2];
					$datapre3 = explode('_', $val->receive_address)[3];
					$resdatapre1 = AreaModel::get(['area_id' => $datapre1]);
					$address1 = $resdatapre1->area_name;
					$resdatapre2 = AreaModel::get(['area_id' => $datapre2]);
					$address2 = $resdatapre2->area_name;
					$resdatapre3 = AreaModel::get(['area_id' => $datapre3]);
					$address3 = $resdatapre3->area_name;
					$datano['receive_address'] = $address1 . ' ' . $address2 . ' ' . $address3;

					$datano['receive_phone'] = $val->receive_phone;
					$datano['is_default'] = $val->is_default;
					$datano['detail_address'] = $val->detail_address;
					$datano['uid'] = $val->uid;
					$data[] = $datano;
				} else if ($val->is_default == 0) {
					$datano['receive_id'] = $val->receive_id;
					$datano['receive_name'] = $val->receive_name;
					$datapre1 = explode('_', $val->receive_address)[1];
					$datapre2 = explode('_', $val->receive_address)[2];
					$datapre3 = explode('_', $val->receive_address)[3];
					$resdatapre1 = AreaModel::get(['area_id' => $datapre1]);
					$address1 = $resdatapre1->area_name;
					$resdatapre2 = AreaModel::get(['area_id' => $datapre2]);
					$address2 = $resdatapre2->area_name;
					$resdatapre3 = AreaModel::get(['area_id' => $datapre3]);
					$address3 = $resdatapre3->area_name;
					$datano['receive_address'] = $address1 . ' ' . $address2 . ' ' . $address3;

					$datano['receive_phone'] = $val->receive_phone;
					$datano['is_default'] = $val->is_default;
					$datano['detail_address'] = $val->detail_address;
					$datano['uid'] = $val->uid;
					$data[] = $datano;
				}

			}
			$this->assign('receiveAddress', $data);
		}
		return $this->fetch();
	}

	//查询市
	public function city(Request $request)
	{
		$privince = $request->post('privince');
		$city = AreaModel::where(['pid' => $privince, 'area_deepth' => 1])->field('area_id, area_name')->select();
		echo json_encode(['value' => 2, 'city' => $city]);
	}

	//查询县
	public function country(Request $request)
	{
		$country = $request->post('country');
		$country = AreaModel::where(['pid' => $country, 'area_deepth' => 2])->field('area_id, area_name')->select();
		echo json_encode(['value' => 3, 'country' => $country]);
	}

	//保存收货地址
	public function addressInsert(Request $request)
	{
		$data['receive_name'] = $request->post('user');
		$data['receive_phone'] = $request->post('phone');
		$data['receive_address'] = $request->post('detailId');
		$data['detail_address'] = $request->post('detailAdd');
		$data['uid'] = Cookie::get('uid');
		$data['create_time'] = date('Y-m-d H:i:s');
		$result = ReceiveModel::create($data);
		if ($result) {
			echo json_encode(['value' => 4]);
		} else {
			echo json_encode(['value' => 5]);
		}
	}

	//删除默认收货地址
	public function delAddress(Request $request)
	{
		$delId = $request->post('id');
		$result = ReceiveModel::where(['receive_id' => $delId])->delete();
		if ($result) {
			echo json_encode(['state' => 1]);
		} else {
			echo json_encode(['state' => 2]);
		}
	}

	//删除非默认地址
	public function delAdd(Request $request)
	{
		$id = $request->get('id');
		ReceiveModel::where(['receive_id' => $id])->delete();
		echo "<script>window.location.href='/index/person/address'</script>";
	}

	//修改默认地址
	public function Adddefault(Request $request)
	{
		$aid = $request->get('aid');
		$uid = $request->get('uid');
		$uResult = ReceiveModel::where(['uid' => $uid])->update(['is_default' => 0]);
		$aResult = ReceiveModel::where(['receive_id' => $aid])->update(['is_default' => 1]);
		if ($uResult && $aResult) {
			echo "<script>window.location.href='/index/person/address'</script>";
		} else {
			echo "<script>window.location.href='/index/person/address'</script>";
		}
	}

	//购物车------------------------------------------------------------------------------
	public function shopcart(Request $request)
	{
		//查询购物车中的信息
		$uid = Cookie::get('uid');
//aaa
		$buyData = CartModel::where(['uid' => $uid])->select();
		//查询所有的属性
		$goods = GoodsModel::select();
		$attr = AttrModel::select();
		$this->assign('buyData', $buyData);
		$this->assign('goods', $goods);
		$this->assign('attr', $attr);

		return $this->fetch();
	}

	//提交订单页面
	public function pay(Request $request)
	{

		//查询收件人地址
		$uid = Cookie::get('uid');
		$result = ReceiveModel::where(['uid' => $uid, 'receive_del' => 0])->select();
		if ($result) {
			foreach ($result as $val) {
				if ($val->is_default == 1) {
					$datano['receive_id'] = $val->receive_id;
					$datano['receive_name'] = $val->receive_name;
					$datapre1 = explode('_', $val->receive_address)[1];
					$datapre2 = explode('_', $val->receive_address)[2];
					$datapre3 = explode('_', $val->receive_address)[3];
					$resdatapre1 = AreaModel::get(['area_id' => $datapre1]);
					$address1 = $resdatapre1->area_name;
					$resdatapre2 = AreaModel::get(['area_id' => $datapre2]);
					$address2 = $resdatapre2->area_name;
					$resdatapre3 = AreaModel::get(['area_id' => $datapre3]);
					$address3 = $resdatapre3->area_name;
					$datano['receive_address'] = $address1 . ' ' . $address2 . ' ' . $address3;

					$datano['receive_phone'] = $val->receive_phone;
					$datano['is_default'] = $val->is_default;
					$datano['detail_address'] = $val->detail_address;
					$datano['uid'] = $val->uid;
					$data[] = $datano;
				} else if ($val->is_default == 0) {
					$datano['receive_id'] = $val->receive_id;
					$datano['receive_name'] = $val->receive_name;
					$datapre1 = explode('_', $val->receive_address)[1];
					$datapre2 = explode('_', $val->receive_address)[2];
					$datapre3 = explode('_', $val->receive_address)[3];
					$resdatapre1 = AreaModel::get(['area_id' => $datapre1]);
					$address1 = $resdatapre1->area_name;
					$resdatapre2 = AreaModel::get(['area_id' => $datapre2]);
					$address2 = $resdatapre2->area_name;
					$resdatapre3 = AreaModel::get(['area_id' => $datapre3]);
					$address3 = $resdatapre3->area_name;
					$datano['receive_address'] = $address1 . ' ' . $address2 . ' ' . $address3;

					$datano['receive_phone'] = $val->receive_phone;
					$datano['is_default'] = $val->is_default;
					$datano['detail_address'] = $val->detail_address;
					$datano['uid'] = $val->uid;
					$data[] = $datano;
				}

			}
			$this->assign('receiveAddress', $data);
		}

		//查询物流方式
		$trans = TransferModel::select();
		$this->assign('trans', $trans);

		//查询支付方式
		$payFunc = PayModel::select();
		$this->assign('payFunc', $payFunc);

		//接收购物车传来的数据
		$data = $request->param();
		if (isset($data['items'])) {
			$item = $data['items'];
			foreach ($item as $val) {
				$what['goods_id'] = $val;
				$what['price'] = $data['goodPrice'][$val];
				$what['num'] = $data['num'][$val];
				$what['taste'] = $data['taste'][$val];
				$what['name'] = $data['name'][$val];
				$what['pic'] = $data['pic'][$val];
				$goods[] = $what;
			}
			$this->assign('goods', $goods);
		} else {
			$this->assign('single', $data);
		}


		return $this->fetch();
//		$this->success('aa', '/index/person/index');
	}

	//生成订单
	public function order(Request $request)
	{
		$data = $request->param();

		if ($data) {
			//取出商品信息
			$gid = $data['name'];
			foreach ($gid as $key => $val) {
				$gidarray[] = $key;
			}
			foreach ($gidarray as $val) {
				$good['goods_id'] = $val;
				$good['name'] = $data['name'][$val];
				$good['taste'] = $data['taste'][$val];
				$good['price'] = $data['price'][$val];
				$good['num'] = $data['num'][$val];
				$goods[] = $good;
			}
			//组装订单详情
			if (count($goods) == 1) {
				$goodsData['goods_id'] = $goods[0]['goods_id'];
				$attr_id = AttrModel::get(['attr_name' => $goods[0]['taste']]);
				$goodsData['attr_id'] = $attr_id->attr_id;
				$goodsData['create_time'] = date('Y-m-d H:i:s');
				$goodsData['update_time'] = date('Y-m-d H:i:s');
				$goodsData['should_pay'] = $goods[0]['price'] * $goods[0]['num'];
				$goodsData['last_paid'] = $goodsData['should_pay'];
				$goodsData['buy_num'] = $goods[0]['num'];

				$relResult = OrderDetailModel::create($goodsData);

				$order['detail_id'] = $relResult->detail_id;

				$detail_id[] = $order['detail_id'];
			} else {
				foreach ($goods as $key => $val) {
					$gooddata['goods_id'] = $val['goods_id'];
					$goods_attr = $val['taste'];
					$goods_attr_id = AttrModel::get(['attr_name' => $goods_attr]);
					$gooddata['attr_id'] = $goods_attr_id->attr_id;
					$gooddata['create_time'] = date('Y-m-d H:i:s');
					$gooddata['update_time'] = date('Y-m-d H:i:s');
					$gooddata['should_pay'] = $val['num'] * $val['price'];
					$gooddata['last_paid'] = $val['num'] * $val['price'];
					$gooddata['buy_num'] = $val['num'];
					$relResult = OrderDetailModel::create($gooddata);

					$detail_id[] = $relResult->detail_id;
					$goods_id[] = $val['goods_id'];
				}
				$order['detail_id'] = join(',', $detail_id);
			}

//组装订单总表
			$order['uid'] = Cookie::get('uid');
			$receive_id = ReceiveModel::get(['receive_id' => $data['user']]);
			$order['receive_id'] = $receive_id->receive_id;
			$order['should_pay'] = $data['totalPrice'];
			$order['last_paid'] = $data['totalPrice'];
			$order['create_time'] = date('Y-m-d H:i:s');
			$order['buy_time'] = date('Y-m-d H:i:s', time() + 1800);
			$order['pay_id'] = $data['paymethod'];
			$order['send_id'] = $data['postmethod'];
			$order['trans_money'] = count($gidarray) * 10;
			$order['order_card'] = mt_rand(10000000, 99999999);
			$order['order_desc'] = $data['message'];

			$result = OrderModel::create($order);
			$orderId['order_id'] = $result->order_id;

			OrderDetailModel::where('detail_id', 'in', $detail_id)->update($orderId);

			if ($result) {
				if (isset($goods_id)) {

					CartModel::where('goods_id', 'in', $goods_id)->delete();
				}

				$this->success('订单提交成功', '/index/person/order');
			} else {
				OrderModel::where(['order_id' => $result])->delete();
				$this->success('订单提交失败', '/index/person/shopcart');
			}
		}

		//查询当前用户的订单
		$uid = Cookie::get('uid');
		$order = OrderModel::where(['uid' => $uid])->select();
		$this->assign('order', $order);

		$orderDetail = OrderDetailModel::select();
		$this->assign('orderDetail', $orderDetail);

		$goods = GoodsModel::select();
		$this->assign('goods', $goods);

		$taste = AttrModel::select();
		$this->assign('tastes', $taste);

		return $this->fetch();

	}

	//加入购物车
	public function addcart(Request $request)
	{

		if (Cookie::get('loginBy')) {
			$data['goods_id'] = $request->post('goods_id');
			$data['uid'] = Cookie::get('uid');
			$data['attr_id'] = $request->post('attr_id');
			$data['buy_num'] = $request->post('buy_num');
			$data['create_time'] = date('Y-m-d H:i:s');
			$cart = CartModel::get(['goods_id' => $data['goods_id']]);
			if (!$cart) {
				$result = CartModel::create($data);
			} else {
				$num = $cart->buy_num;
				$num = $num + $data['buy_num'];
				$what['buy_num'] = $num;
				CartModel::where(['goods_id' => $data['goods_id']])->update($what);
			}
			if ($cart || isset($result)) {
				echo json_encode(['state' => 1]);
			} else {
				echo json_encode(['state' => 3]);
			}

		} else {
			echo json_encode(['state' => 2]);
		}
	}

	//修改密码页面-------------------------------------------------
	public function password()
	{
		return $this->fetch();
	}

	//安全修改密码验证密码
	public function passwordCheck(Request $request)
	{
		$password = md5($request->post('pwd'));

		$userResult = UserModel::get(['password' => $password]);
		$shopResult = ShoperModel::get(['shop_password' => $password]);
		$adminResult = AdminModel::get(['admin_password' => $password]);

		if ($userResult || $shopResult || $adminResult) {
			echo json_encode(['value' => 1]);
		} else {
			echo json_encode(['value' => 2]);
		}
	}

	//安全修改密码
	public function modify(Request $request)
	{
		$uid = Cookie::get('uid');
		$loginType = Cookie::get('loginType');

		//接收ajax收据
		$pwd = md5($request->post('pwd'));

		//普通用户
		if ($loginType == 0) {
			$result = UserModel::where(['uid' => $uid])->update(['password' => $pwd]);
			if ($result) {
				echo json_encode(['value' => 3]);    //修改密码成功
			} else {
				echo json_encode(['value' => 4]);    //修改密码失败
			}

			//商家
		} else if ($loginType == 1) {
			$result = ShoperModel::where(['shop_id' => $uid])->update(['shop_password' => $pwd]);
			if ($result) {
				echo json_encode(['value' => 3]);    //修改密码成功
			} else {
				echo json_encode(['value' => 4]);    //修改密码失败
			}

			//管理员
		} else if ($loginType == 2) {
			$result = AdminModel::where(['admin_id' => $uid])->update(['admin_password' => $pwd]);
			if ($result) {
				echo json_encode(['value' => 3]);    //修改密码成功
			} else {
				echo json_encode(['value' => 4]);    //修改密码失败
			}
		}
	}
}